/**
 * 
 */
package stepdefinations;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

import selenium.SeleniumBase;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;

/**
 * @author Pallavi
 *
 */

public class BooksLinkRegression extends SeleniumBase {

	@Given("^As a user I click on \"(.*?)\" links$")
	public void asauserIclickonbookslink(String headerlinks) throws Throwable {
		Assert.assertTrue(isBooksLinkVisisble(headerlinks));
	}

	private boolean isBooksLinkVisisble(String headerlinks) {

		if (driver.findElement(
				By.xpath("//a[contains(text(),'" + headerlinks + "')]"))
				.isDisplayed()) {
			WebElement menu = driver.findElement(By
					.xpath("//a[contains(text(),'" + headerlinks + "')]"));
			Actions builder = new Actions(driver);
			builder.moveToElement(menu).build().perform();
			driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
			builder.moveToElement(menu).click().perform();
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			return true;
		}

		return false;

	}

	private String randomEmail(int length) {
		String allowedChars = "abcdefghijklmnopqrstuvwxyz" + // alphabets
				"1234567890"; // numbers

		String email = "";
		String temp = RandomStringUtils.random(length, allowedChars);
		email = temp + "@test.gmail.com";
		return email;
	}

	@And("^I verify page title \"(.*?)\"$")
	public void i_verify_page_title(String Pagetitle) throws Throwable {
		Assert.assertTrue(isPagetitleVisible(Pagetitle));

	}

	private boolean isPagetitleVisible(String pagetitle) {

		Assert.assertEquals(pagetitle, driver.getTitle());
		return true;
	}

	@Then("^I \"(.*?)\"$")
	public void isortbyvalue(String sortbyvalue) throws Throwable {
		Assert.assertTrue(isSortbyOptionsVisible(sortbyvalue));

	}

	private boolean isSortbyOptionsVisible(String sortbyvalue) {

		if (driver.getTitle().equalsIgnoreCase(
				"nopCommerce demo store. Computers")) {
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			driver.findElement(By.linkText("Desktops")).click();
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			Assert.assertEquals("Desktops",
					driver.findElement(By.cssSelector("h1")).getText());
			driver.findElement(By.id("products-orderby")).isDisplayed();
			Select dropdown = new Select(driver.findElement(By
					.id("products-orderby")));
			dropdown.selectByValue(sortbyvalue);
			return true;
		} else if (driver.getTitle().equalsIgnoreCase(
				"nopCommerce demo store. Electronics")) {
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			{
				driver.findElement(By.linkText("Camera, photo")).click();
				driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
				Assert.assertEquals("Camera, photo",
						driver.findElement(By.cssSelector("h1")).getText());
				if (driver.findElement(By.id("products-orderby")).isDisplayed()) {
					Select dropdown = new Select(driver.findElement(By
							.id("products-orderby")));
					dropdown.selectByValue(sortbyvalue);
					return true;
				}
			}
		} else if (driver.getTitle().equalsIgnoreCase(
				"nopCommerce demo store.Gift Cards")) {
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
			{
				Assert.assertEquals("Gift Cards",
						driver.findElement(By.cssSelector("h1")).getText());
				if (driver.findElement(By.id("products-orderby")).isDisplayed()) {
					Select dropdown = new Select(driver.findElement(By
							.id("products-orderby")));
					dropdown.selectByValue(sortbyvalue);
					// click
					// wait

				}

			}
		}

		else {
			driver.findElement(By.id("products-orderby")).isDisplayed();
			Select dropdown = new Select(driver.findElement(By
					.id("products-orderby")));
			dropdown.selectByValue(sortbyvalue);
			return true;
		}

		return false;
	}

	@Then("^I verify if sorted by value \"(.*?)\"$")
	public void i_verify_if_sorted_by_value(String SortybyValue)
			throws Throwable {
		Assert.assertTrue(isSortbyValueVisible(SortybyValue));

	}

	private boolean isSortbyValueVisible(String SortybyValue)
			throws ParseException {
		String[] pagetitle = { "nopCommerce demo store. Camera, photo",
				"nopCommerce demo store. Apparel & Shoes",
				"nopCommerce demo store. Digital downloads",
				"nopCommerce demo store. Jewelry",
				"nopCommerce demo store. Gift Cards" };
		if (driver.getTitle()
				.equalsIgnoreCase("nopCommerce demo store. Books ")) {
			// driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

			String price1 = driver
					.findElement(
							By.xpath("//div[@class='product-grid']/div[1]/div/div[2]/div[3]/div[1]/span[2]"))
					.getText();
			price1 = price1.substring(1);
			System.out.println(price1);
			Float f1 = new Float(price1);
			int i = f1.intValue();
			System.out.println("Value = " + i);
			String price2 = driver
					.findElement(
							By.xpath("//div[@class='product-grid']/div[2]/div/div[2]/div[3]/div[1]/span[2]"))
					.getText();
			price2 = price2.substring(1);
			System.out.println(price2);
			Float f2 = new Float(price2);
			int i1 = f2.intValue();
			System.out.println("Value = " + i1);
			System.out.println("i=" + i);
			System.out.println("i1=" + i1);

			if (SortybyValue != null) {
				System.out.println("===== in if");
				if (i < i1) {

				}

				return true;
			}

		}

		else if (driver.getTitle().equalsIgnoreCase(
				"nopCommerce demo store. Desktops")) {
			String price1 = driver
					.findElement(
							By.xpath("//div[@class='product-grid']/div[1]/div/div[2]/div[3]/div[1]/span"))
					.getText();
			price1 = price1.substring(1);
			Float f1 = new Float(price1);
			int i = f1.intValue();
			String price2 = driver
					.findElement(
							By.xpath("//div[@class='product-grid']/div[2]/div/div[2]/div[3]/div[1]/span"))
					.getText().substring(1);

			NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
			int i1 = nf.parse(price2).intValue();
			System.out.println("value==" + i1);

			if (SortybyValue != null) {
				System.out.println("===== in if");
				if (i < i1)
					;

				return true;
			}

		}

		for (int a = 0; a < pagetitle.length; a++) {
			if (pagetitle != null) {
				String price1 = driver
						.findElement(
								By.xpath("//div[@class='product-grid']/div[1]/div/div[2]/div[3]/div[1]/span"))
						.getText();
				price1 = price1.substring(1);
				System.out.println(price1);
				Float f1 = new Float(price1);
				int i = f1.intValue();
				System.out.println("Value = " + i);
				String price2 = driver
						.findElement(
								By.xpath("//div[@class='product-grid']/div[2]/div/div[2]/div[3]/div[1]/span"))
						.getText();
				price2 = price2.substring(1);
				System.out.println(price2);
				Float f2 = new Float(price2);
				int i1 = f2.intValue();
				System.out.println("Value = " + i1);
				System.out.println("i=" + i);
				System.out.println("i1=" + i1);

				if (SortybyValue != null) {
					System.out.println("===== in if");
					if (i < i1) {

					}

					return true;

				}
				return false;
			}

		}
		return false;

	}

	@Then("^I click on Add to cart$")
	public void i_click_on_Add_to_cart() throws Throwable {
		Assert.assertTrue(isAddToCartVisible());
	}

	private boolean isAddToCartVisible() {

		if (driver
				.findElement(
						By.xpath("html/body/div[4]/div[1]/div[4]/div[2]/div[2]/div[2]/div[3]/div[1]/div/div[2]/div[3]/div[2]/input"))
				.isDisplayed()) {
			driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

			driver.findElement(
					By.xpath("html/body/div[4]/div[1]/div[4]/div[2]/div[2]/div[2]/div[3]/div[1]/div/div[2]/div[3]/div[2]/input"))
					.click();

			driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);

			return true;
		}
		return false;
	}

	@Then("^I click on shopping cart link$")
	public void i_click_on_shopping_cart_link() throws Throwable {
		Assert.assertTrue(isShoppingCartLinkVisible());
	}

	private boolean isShoppingCartLinkVisible() throws Exception {
		String[] labels = { "Recipient's Name:", "Recipient's Email:",
				"Your Name:", "Your Email:", "Message:", "Add:" };
		if (driver.getTitle().equalsIgnoreCase(
				"nopCommerce demo store. $5 Virtual Gift Card")) {
			try {

				for (String string : labels) {

					if (string.equalsIgnoreCase("Recipient's Name:")) {

						driver.findElement(By.id

						("giftcard_1_RecipientName")).sendKeys(
								RandomStringUtils.random(10,
										"abcdefghijklmnopqrstuvwxyz"));
						Thread.sleep(1000);
					} else if (string.equalsIgnoreCase("Recipient's Email:")) {
						driver.findElement(By.id

						("giftcard_1_RecipientEmail"))
								.sendKeys(randomEmail(10));
						Thread.sleep(1000);
					} else if (string.equalsIgnoreCase("Your Name:")) {
						driver.findElement(By.id

						("giftcard_1_SenderName")).sendKeys(
								RandomStringUtils.random(10,
										"abcdefghijklmnopqrstuvwxyz"));
						Thread.sleep(1000);

					} else if (string.equalsIgnoreCase("Your Email:")) {
						driver.findElement(By.id

						("giftcard_1_SenderEmail")).sendKeys(randomEmail(10));
						Thread.sleep(1000);
					} else if (string.equalsIgnoreCase("Message:")) {

						driver.findElement(By.id

						("giftcard_1_Message"))
								.sendKeys("Hi how are you doing");
						Thread.sleep(1000);
					}

					else if (driver.findElement(By.id("add-to-cart-button-1")).isDisplayed()){	
						driver.findElement(By.id("add-to-cart-button-1"))
								.click();
						
						Thread.sleep(1000);
						driver.findElement(By.className("cart-label")).click();
						Thread.sleep(1000);
						
					}
				}
				return true;

			} catch (NoSuchElementException e) {
				e.printStackTrace();

			}
		} else if (driver.findElement(By.className("cart-label")).isDisplayed()) {
			Thread.sleep(1000);
			driver.findElement(By.className("cart-label")).click();
			return true;

		}
		return false;

	}

	@Then("^I verify \"(.*?)\"$")
	public void iverifyshoppingcartpage(String text) throws Throwable {
		Assert.assertEquals(text, isProductNameDisplayed(text));

	}

	private String isProductNameDisplayed(String text) {
		String price = driver
				.findElement(
						By.xpath("//div[@class='order-summary-content']/form/table/tbody/tr[1]/td[4]/span[2]"))
				.getText();
		price = price.substring(1);
		System.out.println("Price=" + price);
		Float x = new Float(price);
		int a = x.intValue();
		System.out.println("value==" + a);
		String quantity = driver
				.findElement(
						By.xpath("html/body/div[4]/div[1]/div[4]/div/div/div[2]/div/form/table/tbody/tr/td[5]/input"))
				.getAttribute("value");
		System.out.println("Quantity= " + quantity);
		Float y = new Float(quantity);
		int b = y.intValue();

		// subTotal = x * y;
		String total = driver
				.findElement(
						By.xpath("//div[@class='order-summary-content']/form/table/tbody/tr[1]/td[6]/span[2]"))
				.getText();
		total = total.substring(1);
		Float z = new Float(total);
		int c = z.intValue();
		System.out.println("c==" + c);
		Assert.assertEquals(c, a * b);
		return driver.findElement(By.linkText(text)).getText();
	}
}
